package com.qf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/18 21:48
 */

@Configuration
public class RedisTemplateConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
        //1. 创建RedisTemplate对象,并连接Redis
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        //2.设置连接Redis的信息
        redisTemplate.setConnectionFactory(connectionFactory);

        //3. 设置Key的序列化方式为字符串，Key，HashKey
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        //4. 设置Value的序列化方式JSON，Jackson   Key，KeyValue
        Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(String.class);
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        //5.指定生效
        redisTemplate.afterPropertiesSet();
        //6. 返回
        return redisTemplate;
    }
}
